<template>

  <div class=" page page-draw-index  ">
    <div class="p-4 bg-white">
      <div class="page-header bg-white  text-black font-bold text-3xl p-b-2">
        我的作品
      </div>
      <div class="status-tabs bg-white py-2">
        <div class="item status11" @click="changeType('noworkinfo')" :class="[{ active: logTypes == 'noworkinfo' }]">
          未发布
        </div>
        <div class="item status12" :class="[{ active: logTypes == 'hasworkinfo' }]" @click="changeType('hasworkinfo')">
          已发布
        </div>
      </div>

      <div class="min-w-full bg-white pic-container relative block" v-if="logTypes == 'noworkinfo'">

        <div class="emptycon flex-grow flex items-center justify-center w-full h-full" v-if="!comfyTasks.length">

          <div class="empty flex">
            <div class="left">
              <img src="/icons/draw-icon6.png" alt="图标1" class="w-65 h-45" />

            </div>
            <div class="right">
              <div class="intro-hd">暂时还没有生成图片</div>
            </div>
          </div>
        </div>
        <div class="genpics flex flex-wrap ">
          <div class=" " v-for="(task, index) in comfyTasks" :key="task.prompt_id">
            <ComfyCptTaskItem :taskItem="task" :width="150" :height="150" @clickPubWorkinfo="clickPubWorkinfo"
              @downloadImage="downloadTaskImage(task)" />
          </div>
        </div>

        <div class="more relative flex justify-center m-4" v-if="hasMore" @click="getMore">
          <el-button type="primary">加载更多</el-button>
        </div>
      </div>
      <div class="min-w-full bg-white pic-container relative block " v-if="logTypes == 'hasworkinfo'">

        <div class="emptycon flex-grow flex items-center justify-center w-full h-full" v-if="!workinfos.length">

          <div class="empty flex">
            <div class="left">
              <img src="/icons/draw-icon6.png" alt="图标1" class="w-65 h-45" />

            </div>
            <div class="right">
              <div class="intro-hd">暂时还没有生成图片</div>
            </div>
          </div>
        </div>
        <div class="genpics flex flex-wrap " v-if="logTypes == 'noworkinfo'">
          <div class=" " v-for="(task, index) in comfyTasks" :key="task.prompt_id">
            <ComfyCptTaskItem :taskItem="task" :width="150" :height="150" @clickPubWorkinfo="clickPubWorkinfo" />
          </div>
        </div>
        <div class="genpics flex flex-wrap " v-if="logTypes == 'hasworkinfo'">
          <div class="workinfoitem" v-for="(work, index) in workinfos" :key="work.id">
            <PublicCptWorkInfoItem :workInfo="work" :width="150" :height="150" :showAuthor="false"
              @clickEditWorkinfo="clickEditWorkinfo" @deleteWorkinfoSuccess="deleteWorkinfoSuccess">
            </PublicCptWorkInfoItem>
          </div>
        </div>
        <div class="more relative flex justify-center m-4" v-if="hasMore" @click="getMore">
          <el-button type="primary">加载更多</el-button>
        </div>
      </div>
    </div>
  </div>

  <ClientOnly>
    <PublicCptPubWorkInfoModal v-model:visible="pubmodalVisible" :currentTaskInfo="currentTaskInfo"
      @pubworkSuccess="pubworkSuccess" />
  </ClientOnly>
  <ClientOnly>
    <PublicCptEditWorkInfoModal v-model:visible="editmodalVisible" :currentWorkInfo="currentWorkInfo"
      @editworkSuccess="editworkSuccess" />
  </ClientOnly>
</template>
<script setup>
import { ref } from 'vue'
import { postAiDrawDS, postAIMyWorkflowLogs, postAIMyWorks, postAIWorkflowLogs, postSendDrawTask } from '../../service/yapi';
import { useAppStore } from "~/stores/app";
import PublicCptPubWorkInfoModal from '~/components/public/CptPubWorkInfoModal.vue';
import PublicCptEditWorkInfoModal from '~/components/public/CptEditWorkInfoModal.vue';
import ComfyCptTaskItem from '~/components/comfy/CptTaskItem.vue';
import PublicCptWorkInfoItem from '~/components/public/CptWorkInfoItem.vue';

let app = useAppStore();
let { downloadByUrl } = app;
let prompt = ref('Cartoon Icon')
let gennum = ref(1)
let menuIndex = ref(0)
let cost = computed(() => {
  return gennum.value * 8
})
let workinfos = ref([])
let comfyTasks = ref([])

let downloadTaskImage = (task) => {

  downloadByUrl({ url: task.outputPics.split(',')[0], name: '图片' });

}
let pagination = ref({
  total: 0,
  page: 1,
  size: 10
});
function resetPagination() {
  pagination.value = {
    total: 0,
    page: 1,
    size: 10
  };
  comfyTasks.value = []
  workinfos.value = []
}
let hasMore = computed(() => {
  return pagination.value.total >= pagination.value.page * pagination.value.size;
});


const canvas = ref(null);

let activeWorkflowId = ref(null)
let logTypes = ref('noworkinfo')
let changeType = (type) => {
  logTypes.value = type
  resetPagination();
  getGenPics()


}
let getGenPics = async () => {
  let res = ''
  if (logTypes.value == 'noworkinfo') {
    res = await postAIMyWorkflowLogs({
      type: logTypes.value,
      page: pagination.value.page,
      size: pagination.value.size
    })

    if (res.code == 1000) {
      let { list, pagination: paginationRes } = res.data;
      pagination.value = paginationRes
      comfyTasks.value = [
        ...comfyTasks.value,
        ...list.map(item => {
          return {
            id: item.id,
            prompt_id: item.prompt_id,
            outputPics: item.outputPics,
            workinfos: item.workinfos,
            status: {
              completed: item.outputPics ? true : false
            }
          }
        })
      ]
    }
  } else if (logTypes.value == 'hasworkinfo') {
    res = await postAIMyWorks({
      type: logTypes.value,
      page: pagination.value.page,
      size: pagination.value.size
    })

    if (res.code == 1000) {
      let { list, pagination: paginationRes } = res.data;
      pagination.value = paginationRes
      workinfos.value = [
        ...workinfos.value,
        ...list
      ]
    }
  }


}

onMounted(() => {
  window.scrollTo(0, 0);
  getGenPics()
});
function getMore() {
  let { total, page, size } = pagination.value;

  if (page * size < total) {
    pagination.value.page = page + 1;
    getGenPics();
  } else {
    ElMessage.warning("没有更多啦，快去创作吧");
  }
}


// 定义防抖函数
function debounce(func, wait) {
  let timeout;
  return function (...args) {
    const context = this;
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(context, args), wait);
  };
}

let baseParams = {
  negative_prompt: "EasyNegative,bad_pictures,paintings,ng_deepnegative_v1_75t,sketches,nsfw,negative_hand-neg,(worst quality:2),(low quality:2),(normal quality:2),lowres,((monochrome)),((grayscale)),skin spots,acnes,skin blemishes,age spot,glans,extra fingers,fewer fingers,((watermark:2)),(white letters:1),(multi nipples),bad anatomy,bad hands,text,error,missing fingers,missing arms,missing legs,extra digit,fewer digits,cropped,worst quality,jpeg artifacts,signature,watermark,username,bad feet,Multiple people,blurry,poorly drawn hands,poorly drawn face,mutation,deformed,extra limbs,extra arms,extra legs,malformed limbs,fused fingers,too many fingers,long neck,cross-eyed,mutated hands,polar lowres,bad body,bad proportions,gross proportions,wrong feet bottom render,abdominal stretch,briefs,knickers,kecks,thong,fused fingers,bad body,bad-picture-chill-75v,bad proportion body to legs,wrong toes,extra toes,missing toes,weird toes,2 body,2 pussy,2 upper,2 lower,2 head,3 hand,3 feet,extra long leg,super long leg,mirrored image,mirrored noise,(bad_prompt_version2:0.8),aged up,old,short legs,3 leg,teeth,white background,simple background,nsfw,bad-picture-chill-75v,badhandv4,bad anatomy,ugly,mutated hands,blurry,fused fingers,too many fingers,EasyNegative,bad_pictures,paintings,ng_deepnegative_v1_75t,sketches,nsfw,negative_hand-neg,(worst quality:2),(low quality:2),(normal quality:2),lowres,((monochrome)),((grayscale)),skin spots,acnes,skin blemishes,age spot,glans,extra fingers,fewer fingers,((watermark:2)),(white letters:1),(multi nipples),bad anatomy,bad hands,text,error,missing fingers,missing arms,missing legs,extra digit,fewer digits,cropped,worst quality,jpeg artifacts,signature,watermark,username,bad feet,Multiple people,blurry,poorly drawn hands,nsfw,nsfw",
  cfg_scale: 1,
  denoising_strength: 0.8,
  num_inference_steps: 1
}
// 读取 canvas 内容并转换为 Base64
const readCanvas = async () => {
  const dataURL = canvas.value.toDataURL('image/png');
  let res = await postAiDrawDS({
    canvas_img: dataURL,
    num_images: gennum.value,
    positive_prompt: prompt.value,
    ...baseParams


  }).catch(err => {
    console.log("%c Line:220 🥚 err", "color:#42b983", err);

  });
  if (res && res.code == 1000) {
    genPics.value = res.images
  }
  console.log("%c Line:217 🥥 res", "color:#fca650", res);
};




let pubmodalVisible = ref(false)
let currentTaskInfo = ref({
  id: ""
})
let clickPubWorkinfo = ({ taskItem }) => {

  currentTaskInfo.value.id = taskItem.id
  pubmodalVisible.value = true
}
let pubworkSuccess = ({ id }) => {
  pubmodalVisible.value = false
  comfyTasks.value = comfyTasks.value.filter(item => {
    return item.id != id
  })

}
let deleteWorkinfoSuccess = ({ id }) => {
  workinfos.value = workinfos.value.filter(item => {
    return item.id != id
  })
}

let editmodalVisible = ref(false)
let currentWorkInfo = ref({
  id: "",
  name: ""
})
let clickEditWorkinfo = (workInfo) => {
  currentWorkInfo.value = workInfo

  editmodalVisible.value = true
}
let editworkSuccess = ({ id }) => {
  editmodalVisible.value = false
  resetPagination();
  getGenPics()

}
definePageMeta({ auth: false });
</script>

<style lang="scss">
.page-draw-index {

  .status-tabs {
    display: flex;

    .item {
      width: 101px;
      height: 38px;
      line-height: 38px;
      text-align: center;
      background: #F3F4F9;
      border-radius: 9px 9px 9px 9px;
      color: #1D255A;
      opacity: 1;
      cursor: pointer;

      &.active {
        color: #fff;
        background: #1E255A;
      }
    }

    .status11 {
      border-radius: 9px 0px 0px 9px;
    }

    .status12 {
      border-radius: 0px 9px 9px 0px;
    }
  }

  .genpic {
    &:hover .btn-append {
      display: block;
    }

    .workinfoitem {}
  }
}
</style>